package com.chuanke.ckfamily.service.user.impl;

import com.chuanke.ckfamily.dao.base.CkUtil;
import com.chuanke.ckfamily.dao.base.Page;
import com.chuanke.ckfamily.dao.social.model.Family;
import com.chuanke.ckfamily.dao.social.model.FamilyMember;
import com.chuanke.ckfamily.dao.user.UserDao;
import com.chuanke.ckfamily.dao.user.model.User;
import com.chuanke.ckfamily.dao.user.model.UserRelation;
import com.chuanke.ckfamily.service.base.FailCode;
import com.chuanke.ckfamily.service.base.FamilyValidator;
import com.chuanke.ckfamily.service.common.CacheService;
import com.chuanke.ckfamily.service.common.CacheService.KEY_PREFIX;
import com.chuanke.ckfamily.service.common.SysConfigService;
import com.chuanke.ckfamily.service.common.WyFriendService;
import com.chuanke.ckfamily.service.common.WyService;
import com.chuanke.ckfamily.service.common.impl.RedisLockUtil;
import com.chuanke.ckfamily.service.constant.FamilyConstance;
import com.chuanke.ckfamily.service.constant.SysConfigKeyEnum;
import com.chuanke.ckfamily.service.exception.CFException;
import com.chuanke.ckfamily.service.social.FamilyMemberService;
import com.chuanke.ckfamily.service.social.FamilyService;
import com.chuanke.ckfamily.service.social.SpecialRelationService;
import com.chuanke.ckfamily.service.user.FriendApplyService;
import com.chuanke.ckfamily.service.user.UserRelationService;
import com.chuanke.ckfamily.service.user.UserService;
import com.chuanke.ckfamily.service.user.thread.LoadFansThread;
import com.chuanke.ckfamily.service.user.thread.WyFriendThread;
import com.chuanke.ckfamily.service.util.CkServerUtil;
import com.chuanke.ckfamily.service.util.model.UserBalance;
import com.weijie.core.BaseBiz;
import com.weijie.core.util.DateUtils;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Transactional(rollbackFor=Exception.class)
public class UserServiceImpl extends BaseBiz<User, UserDao> implements UserService {
	
	/*
	 * 首页搜索默认结果集数量
	 */
	private static final int page_homeSearch = 3;

	@Autowired
	private CacheService cacheService;

	@Override
	public void updateBatch(User entity, List<Long> ids) {
		super.updateBatch(entity, ids);
	}

	@Autowired
	private WyService wyService;
	
    @Autowired
	private SpecialRelationService specialRelationService;
    
    @Autowired
	private UserRelationService userRelationService;

    @Autowired
   	private FriendApplyService friendApplyService;
    
    @Autowired
	private FamilyService familyService;
    
    @Autowired
	private FamilyMemberService familyMemberService;
    
    @Autowired
	private SysConfigService sysConfigService;
    
    @Autowired
	private WyFriendService wyFriendService;

	private static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

	@Override
	public void save(User user) {
		User saved = super.findById(user.getId());
		if (saved == null) {
			baseDao.add(user);
			cacheService.set(CacheService.KEY_PREFIX.user_.name() + user.getId(), baseDao.findById(user.getId()));

		} else {
			User updateUser = new User();
			updateUser.setId(user.getId());
			updateUser.setNick_name(user.getNick_name());
			updateUser.setReal_name(user.getReal_name());
			if (StringUtils.isNotEmpty(user.getMobile())) {
				updateUser.setMobile(user.getMobile());
			}
			updateUser.setPic(user.getPic());
			update(updateUser);

		}
	}

	@Override
	public void update(User user) {
		baseDao.update(user);
		logger.debug("update user ={}, isHeader={}", user.getId(), user.getIs_header());
		cacheService.delete(CacheService.KEY_PREFIX.user_.name() + user.getId());
	}

	@Override
	public void checkUserFans(Long uid) {
		User user = CkServerUtil.loadUser(uid);
		if (user == null) {
			return;
		}

		Integer fansNum = user.getFansNum();

		Map<String,Object> param = new HashMap<>(1);
		param.put("uid",user.getId());
		Integer fansCount = baseDao.searchFansCount(param);

		logger.debug("loadFrom ck ================> fansNum={},fansCount={}",fansNum,fansCount);
		if(fansNum != null && (fansCount == null || fansNum.intValue() != fansCount.intValue())){
			logger.debug("begin load fans");
			LoadFansThread.load(this, uid);
		}
	}

	@Override
	public List<Long> findAllUserId() {
		return baseDao.findAllUserId();
	}

	@Override
	public User findById(Long uid) throws CFException {
		logger.debug("find user by id ={}, baseDao={}", uid, baseDao.getClass().getName());
		if (uid == null) {
			return null;
		}

		User user = (User) cacheService.get(CacheService.KEY_PREFIX.user_.name() + uid);
		if (user == null) {
			user = baseDao.findById(uid);
			if (user == null) {
				user = CkServerUtil.loadUser(uid);
				if (user != null) {
					baseDao.add(user);
				}
			}

			if (user == null) {
				logger.error("用户不存在 id ={}", uid);
				throw new CFException(FailCode.USER_NOT_EXIST);
			}

			cacheService.set(CacheService.KEY_PREFIX.user_.name() + uid, user);
		}

		return user;
	}

	@Override
	public User findByToken(String token) {
		return baseDao.findByToken(token);
	}

	@Override
	public List<User> findByPhone(Long uid, String phone) throws CFException {
		if (StringUtils.isEmpty(phone)) {
			throw new CFException(FailCode.APP, "电话号码不能为空");
		}

		Map<String, Object> param = new HashMap<>(2);
		param.put("uid", uid);
		param.put("phone", phone);

		return baseDao.findUserByPhone(param);
	}

	@Override
	public User login(Long uid) throws CFException,Exception {
		User user = findById(uid);
		if (user == null) {
			logger.error("重新登录================>token={}",uid);
			throw new CFException(FailCode.RELOGIN);
		}
		RedisLockUtil lockUtil = null;
		FamilyMember familyMember = familyMemberService.findByUserId(uid);

		User update = new User();
		update.setId(uid);
		if (StringUtils.isEmpty(user.getWy_token())) {
			
			update.setWy_token(wyService.registUser(user));
			
			new WyFriendThread(uid, this, wyService).start();
			
			if (familyMember != null) {
				//判断网易云信是否加入群成功，不成功则加入
				Family family = familyService.findById(familyMember.getFamily_id());
				try {
					lockUtil = cacheService.getLock(KEY_PREFIX.move_user_.name() + uid);
					wyService.checkTeamMember(family, familyMember, user.getUser_no());
				} catch (Exception e) {
					e.printStackTrace();
				}finally {
					if (lockUtil != null) {
						lockUtil.unlock();
					}
				}
			}
			
		}
		update.setLogin_time(new Timestamp(System.currentTimeMillis()));
		update.setActive_time(new Timestamp(System.currentTimeMillis()));
		update(update);
		
		if (familyMember == null) {
			try {
				lockUtil = cacheService.getLock(KEY_PREFIX.move_user_.name() + uid);
				familyService.addFamilyBylogin(uid, null);
			}catch (Exception e) {
				e.printStackTrace();
			}
			finally {
				if (lockUtil != null) {
					lockUtil.unlock();
				}
			}
		}
		Family family = familyService.findFamilyByUserId(uid);
		user = findById(uid);
		user.setFamilyId(family.getTid().toString());
		return user;
	}

	@Override
	public User findByUserNo(String userNo) throws CFException {
		User user = baseDao.findByUserNo(userNo);
		if(user==null){
			return null;
		}

		return findById(user.getId());
	}


	public User findProxyUser(Long rid, Long did) throws CFException {
		User requestUser = findById(rid);
		User destUser = findById(did);

		String remarkName = getRemarkName(requestUser, destUser);
		if (StringUtils.isNotEmpty(remarkName)) {
			destUser.setNick_name(remarkName);
		}

		return destUser;
	}

	@Override
	public Map<String,Object> getFans(Long uid, String date,String page) throws CFException {
		User user = findById(uid);
		if (user == null) {
			throw new CFException(FailCode.USER_NOT_EXIST);
		}
		Map<String,Object> result = new HashMap<>();
		//我的上线
		User mySuper = findBySuperId(uid);
		if(mySuper!=null){
			String remarkName = getRemarkName(user, mySuper);
			mySuper.setRemark_name(remarkName);
		}
		result.put("mySuper", mySuper);

		if(date == null || date.trim().equals("")){
			// 没有传入date值 直接返回全部数据
			if(page == null || page.trim().equals("")){
				List<User> allFans = this.getAllFans(uid);
				result.put("newFans",allFans);
				setNowTime(result);
				logger.debug("my  fans result ==========>uid={},result={}",uid,result.size());
				return  result;
			}

			List<User> allFans = this.getFans(uid,Integer.parseInt(page));
			result.put("newFans",allFans);
			setNowTime(result);
			logger.debug("my  fans result ==========>uid={},result={}",uid,result);
			return  result;

		} else {
            String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(Long.parseLong(date)));
			List<User> newFans = this.getNewFans(uid,time);
			List<User> updateFans = this.getUpdateFans(uid,time);
			result.put("newFans",newFans);
			result.put("updateFans",updateFans);
			setNowTime(result);
			logger.debug("my  fans result ==========>uid={},result={}",uid,result);
			return result;
		}
	}
	private void setNowTime(Map<String,Object> result){
		result.put("date",new Timestamp(System.currentTimeMillis()));
	}
	private List<User> getAllFans(Long uid){
		Map<String,Object> param = new HashMap<>();
		param.put("uid",uid);
		List<User> allFans = this.baseDao.findUserFans(param);
		return allFans;
	}
	private List<User> getNewFans(Long uid,String time){
		Map<String,Object> param = new HashMap<>();
		param.put("uid",uid);
		param.put("create_time",time);
		return this.baseDao.findUserFans(param);
	}
	private List<User> getUpdateFans(Long uid,String time){
		Map<String,Object> param = new HashMap<>();
		param.put("uid",uid);
		param.put("update_time",time);
		return this.baseDao.findUserFans(param);
	}

	@Override
	public List<User> getFans(Long uid, int page) throws CFException {
		if (uid == null) {
			throw new CFException(FailCode.APP, "用户上级id为空");
		}
		Map<String, Object> param = new HashMap<>(3);
		Page p = new Page(page);
		param.put("uid", uid);
		param.put("start", p.getPageNo());
		param.put("length", p.getPageSize());
		return this.baseDao.findUserFans(param);
	}

	@Override
	public Map<String, Object> updateRemarkName(Long uid, Long tuserId, String remarkName) throws Exception {
		Map<String, Object> result=new HashMap<>();
		if(uid == null){
			throw new CFException(FailCode.USER_NOT_EXIST);
		}
		if(tuserId == null){
			throw new CFException(FailCode.USER_NOT_EXIST);
		}
		if(uid==tuserId){
			throw new CFException(FailCode.PARAMS_ERROR);
		}

		User user = this.findById(uid);
		User tuser = this.findById(tuserId);
		if(user == null || tuser == null){
			throw new CFException(FailCode.USER_NOT_EXIST);
		}
		if (StringUtils.isBlank(remarkName)
				|| remarkName.length() > FamilyValidator.remarkName_length) {
			throw new CFException(FailCode.PARAMS_ERROR,"备注应该在0-"+FamilyValidator.remarkName_length+"位字符之间");
		}
		
		//上级修改下级备注
		User userParam=new User();
		if(uid.equals(tuser.getSuper_id())){
			userParam.setRemark_name(remarkName);//上级对下级的备注
			userParam.setId(tuser.getId());
			this.update(userParam);
			result.put("type", 1);
			if(tuser.hasWyId()){
				wyService.addFriend(user.getUser_no(), tuser.getUser_no());
				wyService.updateFriend(user.getUser_no(), tuser.getUser_no(), remarkName, null);
			}
			logger.debug("updateRemarkName======>上级修改下级备注.uid={},tid={},remarkName={}",uid,tuserId,remarkName);

		}else if(tuser.getId().equals(user.getSuper_id())){//下级修改上级备注
			userParam.setId(user.getId());
			userParam.setSuper_remark_name(remarkName);
			this.update(userParam);
			result.put("type", 1);
			if(tuser.hasWyId()){
				wyService.addFriend(user.getUser_no(), tuser.getUser_no());
				wyService.updateFriend(user.getUser_no(), tuser.getUser_no(), remarkName, null);
			}
			logger.debug("updateRemarkName======>下级修改上级备注.uid={},tid={},remarkName={}",uid,tuserId,remarkName);

		}else{
			result.put("type", 2);
			userRelationService.updateFriendRemark(uid, tuserId, remarkName);

			logger.debug("updateRemarkName======>修改好友备注.uid={},tid={},remarkName={}",uid,tuserId,remarkName);
		}
		
		cacheService.set(KEY_PREFIX.remark_name_.toString()+user.getId()+"_"+tuser.getId(),remarkName);
		return result;
	}
	
	@Override
	public Map<String, Object> getUserBalance(Long uid, String tuserNo, Integer from)throws CFException,Exception {
		Map<String, Object> result = new HashMap<>();
		
		User user = findById(uid);
		if (user == null) {
			throw new CFException(FailCode.USER_NOT_EXIST);
		}

		if (tuserNo == null) {
			User loadUser = CkServerUtil.loadUser(uid);
			if (loadUser != null) {
				user.setFansNum(loadUser.getFansNum());
			}
			result.put("user", userFormat(user, null));
			result.put("balance", getBalance(uid));

		} else {
			User tuser = findByUserNo(tuserNo);
			if (tuser == null) {
				throw new CFException(FailCode.USER_NOT_EXIST);
			}

			Long tuserId = tuser.getId();
			User loadUser = CkServerUtil.loadUser(tuserId);
			if (loadUser != null) {
				tuser.setFansNum(loadUser.getFansNum());
			}
			formatUserBalanceCode(user, tuser, result, from);
			String applyHi = friendApplyService.getApplyHi(uid, tuserNo);
			result.put("applyHi", applyHi);
			result.put("user", userFormat(tuser,user));
			result.put("balance", getBalance(tuserId));

		}

		return result;
	}

	private Map<String, String> getBalance(Long uid) {
		UserBalance balance = CkServerUtil.loadBalance(uid);
		Map<String, String> balanceMap = new HashMap<>();
		balanceMap.put("total", CkUtil.formateServerMoney(balance.getTotal()));
		balanceMap.put("balance", CkUtil.formateToYuan(balance.getBalance()));

		return balanceMap;
	}

	@Override
	public Map<String, Object> formatUserBalanceCode(User user, User tuser,
			Map<String, Object> result ,Integer from ) throws CFException {
		if (result == null) {
			result = new HashMap<>();
		}
		if(user.getId().equals(tuser.getId())){
			result.put("butCode", 0);
			result.put("blackCode", false);
			result.put("friendCode", false);
			return result;
		}
		// from=1 时 说明是从新的好友页面请求，type返回3
		
		// type 0:无  1:粉丝,2:好友3.通过验证 4加好友 5粉丝-对方网易云信未注册
		
		// is_black 是否拉黑对方 false:未拉黑 true:已拉黑
		
		// is_friend 是否移除好友  false:未移除好友 true：已移除好友
		
		boolean is_super=user.getId().equals(tuser.getSuper_id()) || tuser.getId().equals(user.getSuper_id());
		boolean tIsBlack = specialRelationService.isBlack(tuser.getId(), user.getId());
		boolean isBalck = specialRelationService.isBlack(user.getId(), tuser.getId());

		if(from!=null && from==1){
			result.put("type",3);
			result.put("is_black", tIsBlack);
			result.put("is_friend",false);

		}else if(is_super){
			result.put("type",1);
			result.put("is_black",false);
			result.put("is_friend",false);
			if(!tuser.hasWyId()){
				result.put("type",5);
			}

		}else if(userRelationService.isFriend(user.getId(), tuser.getId())){
			result.put("type",2);
			result.put("is_black", isBalck);
			result.put("is_friend",false);

		}/*else if(tfriendApply!=null && tfriendApply.getType()==FriendApplyType.APPLY.getType()){
			result.put("type",3);
			result.put("is_black",tfriendApply.getIs_black()!=null && tfriendApply.getIs_black()==1);
			result.put("is_friend",false);

		}*/else{
			result.put("type",4);
			result.put("is_black",false);
			result.put("is_friend",false);

		}
		return result;
	}

	@Override
	public Map<String, Object> getUserInfo(Long uid, String tuserNo)throws CFException,Exception {
		Map<String, Object> result = new HashMap<>();
		
		User user = findById(uid);
		if (user == null) {
			throw new CFException(FailCode.USER_NOT_EXIST);
		}
		
		if (tuserNo == null) {
			result.put("user", userFormat(user, null));
		} else {
			User tuser = findByUserNo(tuserNo);
			if (tuser == null) {
				throw new CFException(FailCode.USER_NOT_EXIST);
			}
			boolean is_super=user.getId().equals(tuser.getSuper_id()) || tuser.getId().equals(user.getSuper_id());
			
			//对方是否在自己的黑名单中
			boolean is_black = specialRelationService.isBlack(uid, tuser.getId());
			result.put("is_black", is_black);
			//是否是粉丝
			result.put("is_super", is_super);

			//是否加入免打扰
			boolean is_mute = specialRelationService.isMute(uid, tuser.getId());
			result.put("is_mute", is_mute);
			result.put("user",userFormat(tuser,user));
		}
		return result;
	}
	
	@Override
	public boolean checkIsFans(Long uid, Long sid) throws CFException {
		if(uid == null ||sid == null){
			throw new CFException(FailCode.PARAMS_ERROR);
		}
		User user = findById(uid);
		User suser = findById(sid);
		if(user.getId().equals(suser.getSuper_id()) || suser.getId().equals(user.getSuper_id())){
			return true; // 是粉丝关系
		}
		return false;
	}

	private User userFormat(User tuser, User user) {
		if(tuser==null){
			return null;
		}
		if(user==null){
			return tuser;
		}

		boolean has_fans = user.getId().equals(tuser.getSuper_id()) || tuser.getId().equals(user.getSuper_id());
		if(!has_fans){
			String mobile = tuser.getMobile();
			if(StringUtils.isNotEmpty(mobile) && mobile.length() >= 11){
				String newMobile=mobile.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
				tuser.setMobile(newMobile);
			}
		}

		String remarkName = getRemarkName(user, tuser);
		tuser.setRemark_name(remarkName);
		if(tuser.getSex()==null || tuser.getSex()==0){
			tuser.setSex(1);
		}

		return tuser;
	}
	
	public String getRemarkName(User user, User tuser) {
		try {
			if(user == null || tuser == null){
				return null;
			}

			String remark = (String) cacheService.get(KEY_PREFIX.remark_name_.toString()+user.getId()+"_"+tuser.getId());
			if(StringUtils.isEmpty(remark)){
				if(user!=null && tuser!=null){
					if(user.getId().equals(tuser.getSuper_id())){
						remark =tuser.getRemark_name();
					}else if(tuser.getId().equals(user.getSuper_id())){
						remark= user.getSuper_remark_name();
					}else{
						UserRelation userRelation = userRelationService.getUserRelation(user.getId(), tuser.getId());
						if(userRelation!=null){
							remark=userRelation.getFriend_remark();
						}
					}
				}
				if(StringUtils.isNotEmpty(remark)){
					cacheService.set(KEY_PREFIX.remark_name_.toString()+user.getId()+"_"+tuser.getId(),remark);
				}
				
			}

			return remark;

		} catch (CFException e) {
			e.printStackTrace();

		} catch (Exception e) {
			e.printStackTrace();

		}
		return null;
	}

	@Override
	public Map<String, Object> getMemberInfo(Long uid, String tuserNo,String tid)throws CFException {
		User user= findById(uid);
		if (user == null) {
			throw new CFException(FailCode.USER_NOT_EXIST);
		}
		FamilyMember familyMember = familyMemberService.findByUserId(uid);
		if (familyMember == null) {
			throw new CFException(FailCode.FAMILY_MEMBER_NOT_EXIST);
		}

		Map<String, Object> result = new HashMap<>();
		if(tuserNo==null){
			result.put("familyMember", familyMember);
			result.put("user", userFormat(user,null));
			
		}else{
			User tuser = findByUserNo(tuserNo);
			if (tuser == null) {
				throw new CFException(FailCode.USER_NOT_EXIST);
			}
			FamilyMember tfamilyMember = familyMemberService.findByUserId(tuser.getId());
			if (tfamilyMember == null) {
				throw new CFException(FailCode.FAMILY_MEMBER_NOT_EXIST);
			}
			Family family = familyService.findById(tfamilyMember.getFamily_id());
			FamilyValidator.validateFamilyTid(family, tid);
			
			if (!familyMember.getFamily_id().equals(tfamilyMember.getFamily_id())) {
				throw new CFException(FailCode.FAMILY_TID_MATCH);
			}
			if(familyMember.getFamily_id()!=tfamilyMember.getFamily_id().longValue()){
				throw new CFException(FailCode.FAMILY_MEMBER_NOT_EXIST);
			}
			
			formatMemberInfoCode(user, tuser,result);
			result.put("familyMember", tfamilyMember);
			result.put("user", userFormat(tuser,user));
			

		}

		return result;
	}

	@Override
	public  Map<String, Object>  formatMemberInfoCode(User user,User tuser,Map<String, Object> result)throws CFException {
		
		if (result == null) {
			result = new HashMap<>();
		}
		// kickCode 0:不显示 1：踢出家族
		// muteCode 0:不显示 1：禁言 2解除禁言3已禁言
		if(user.getId().equals(tuser.getId())){
			result.put("muteCode", 0);
			result.put("kickCode", 0);
			return result;
		}
		if (tuser.getIs_header() == 1) {
			result.put("muteCode", 0);
			result.put("kickCode", 0);
			return result;
		}
		FamilyMember tfamilyMember = familyMemberService.findByUserId(tuser.getId());
		if(tfamilyMember==null){
			result.put("muteCode", 0);
			result.put("kickCode", 0);
			return result;
		}
		if (user.getIs_header() == 1) {
			long currentTimeMillis = System.currentTimeMillis();
			long kick_login_time = sysConfigService.getLongValue(SysConfigKeyEnum.kick_login_time.toString(),FamilyConstance.LEADER_LOST_TIME_SPAN);
			boolean is_kick =true;
			if(tuser.getActive_time()!=null){
				 long  loginTime=tuser.getActive_time().getTime();
				 is_kick = (currentTimeMillis - loginTime > kick_login_time);
			}
			result.put("muteCode", tfamilyMember.getMute() == 0 ? 1 : 2);
			result.put("kickCode", is_kick ? 1 : 0);
		} else if (user.getIs_header() == 0) {
			result.put("muteCode", tfamilyMember.getMute() == 0 ? 1 : 3);
			result.put("kickCode",0);
		}
		return result;
	}

	@Override
	public List<User> searchUser(Map<String, Object> Map) {
		
		return baseDao.searchUser(Map);
	}
	
	public static void main(String[] args) {
		Date t=new Date(1505812776000l);
		String a = DateUtils.dateToString(t);
		System.out.println(a);
	}

	@Override
	public Map<String, Object> homeSearch(Long uid, String keyword) throws Exception {
		logger.debug("homesearch===========> keyword={}", keyword);
		if (keyword == null || StringUtils.isEmpty(keyword.trim())) {
			Map<String, Object> eresult = new HashMap<>();
			eresult.put("show_phone", isPhone(keyword));
			return eresult;
		}

		Map<String, Object> param=new HashMap<>();
		param.put("uid", uid);	
		param.put("keyword", keyword);
		Page page=new Page(0,page_homeSearch);

		Integer fansFamilyCount = baseDao.searchFansFamilyCount(param);
		if (fansFamilyCount == null) {
			fansFamilyCount = 0;
		}
		List<Map<String, Object>> fansFamily = baseDao.searchFansFamily(param,page);
		
		Integer fansCount=baseDao.searchFansCount(param);
		if (fansCount == null) {
			fansCount = 0;
		}
		List<Map<String, Object>> fans = baseDao.searchFans(param,page);
		fans=homeSearchFormat(fans,keyword);

		Integer friendCount=baseDao.searchFriendCount(param);
		if (friendCount == null) {
			friendCount = 0;
		}
		List<Map<String, Object>> friend = baseDao.searchFriend(param,page);
		friend=homeSearchFormat(friend,keyword);

		logger.debug("homeSearch =====> fansFamilyCount={}, fansCount={}, friendCount={}, isphone={}", fansFamilyCount, fansCount, friendCount, isPhone(keyword));
		Map<String, Object> result=new HashMap<>();
		if ((fansFamilyCount == 0 && fansCount == 0 && friendCount == 0)
				&& isPhone(keyword)) {
			result.put("show_phone", true);
			List<User> users = findByPhone(uid, keyword);
			if (users != null && users.size() > 0) {
				result.put("user", users.get(0));
			}

		} else {
			result.put("show_phone", false);
			if(fansFamily!=null && !fansFamily.isEmpty()){
				result.put("fansFamily", fansFamily);
				result.put("fansFamilyCount", fansFamilyCount);
			}

			if(fans!=null && !fans.isEmpty()){
				result.put("fans", fans);
				result.put("fansCount", fansCount);
			}

			if(friend!=null && !friend.isEmpty()){
				result.put("friend", friend);
				result.put("friendCount", friendCount);
			}

		}

		return result;
	}
	private List<Map<String, Object>> homeSearchFormat(List<Map<String, Object>> list,String keyword) {
		if(list==null || list.isEmpty()){
			return list;
		}
		for (Map<String, Object> map : list) {
			String remark_name=MapUtils.getString(map, "remark_name");
			if(remark_name!=null && StringUtils.isNotEmpty(keyword) && remark_name.contains(keyword)){
				map.put("nick_name", remark_name);
			}
		}
		return list;
	}

	@Override
	public User findBySuperId(Long uid) throws CFException {
		try {
			User user = findById(uid);
			if (user == null || user.getSuper_id() == null
					|| user.getSuper_id() == 0
					|| uid.equals(user.getSuper_id())) {
				return null;
			}
			return findById(user.getSuper_id());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private boolean isPhone(String phone) {
		Pattern p = Pattern.compile("^1\\d{10}$");
		Matcher m = p.matcher(phone);
		return m.find();
	}
}